package com.cn.qgx428.lazydiary.ui.activity

import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.DatePicker
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.Utils.RecordHelper
import com.cn.qgx428.lazydiary.Utils.SPUtil
import com.cn.qgx428.lazydiary.adapter.RAdapter
import com.cn.qgx428.lazydiary.adapter.RViewHolder
import com.cn.qgx428.lazydiary.db.bean.CBill
import com.cn.qgx428.lazydiary.db.dao.BillDao
import com.cn.qgx428.lazydiary.extension.getCurrenMouth
import com.cn.qgx428.lazydiary.extension.getCurrenMouthWidthYear
import com.cn.qgx428.lazydiary.extension.switchVisible
import com.cn.qgx428.lazydiary.local.LAMessege
import com.cn.qgx428.lazydiary.local.LAction
import com.cn.qgx428.lazydiary.local.LActionWacher
import com.cn.qgx428.lazydiary.local.LManager
import com.cn.qgx428.lazydiary.ui.activity.BaseActivity
import com.cn.qgx428.lazydiary.ui.activity.subActivity.BillModifyActivity
import com.cn.qgx428.lazydiary.ui.activity.subActivity.BillStatisticActivity
import com.cn.qgx428.lazydiary.ui.activity.subActivity.BudgetSettingActivitiy
import kotlinx.android.synthetic.main.activity_bill.*
import kotlinx.android.synthetic.main.activity_bill_add.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*

class BillActivity : BaseActivity(),LActionWacher {

    var billAdapter = BillAdapter(this, R.layout.adapter_bill_record_item)
    var mExpend = ""
    lateinit var currentMouthOfYear: String

    override fun initUI() {
        hindActionBar()
        setStatuBarColor(Color.BLACK)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bill)

        currentMouthOfYear = intent.getStringExtra(MConst.CURRENT_MOUTH_WITH_YEAR)
        initView()
        refreshRecordData()
        //监听
        LManager.newInstance().register(this, LAction.DB_UPDATE_BILL)
        LManager.newInstance().register(this,LAction.ACTION_CHANGE_BUDGET)
    }

    /**
     * 为billAdapter准备数据， 并更新页面相应关键数据
     */
    private fun refreshRecordData() {
        val datas  = BillDao().queryWhereLikeOrder("createTime",currentMouthOfYear,"createTime",false) as MutableList<CBill>
//        val datas = BillDao().getBuilder().
//                orderBy("createTime", false)
//                .where()
//                .like("createTime",currentMouthOfYear)
//                .query()
        billAdapter.setDatas(datas)

        // 更新UI
        var income: Float = 0f
        var expend: Float = 0f
        datas.forEach {
            if (it.type.equals(MConst.BILL_INCOME))
                income = income + (it.total!!.toFloat())
            else
                expend = expend + (it.total!!.toFloat())
        }
        val balance = income - expend
        bill_income.text = income.toString()
        bill_expend.text = expend.toString()
        bill_balance.text = balance.toString()

        mExpend = expend.toString()
        refreshBugdet()
    }

    /**
     * 刷新预算
     */

    private fun refreshBugdet(budget: String = ""){
        var budgetNo = 0f
        if (budget.equals(""))
            budgetNo = SPUtil.getBillBudget().toFloat()
        else{
            budgetNo = budget.toFloat()
        }

        val residue = (budgetNo - mExpend.toFloat())
        if (residue < 0f){
            bill_progress.setProgress(0)
            bill_residue.text = "预算超支: -" + residue.toString()
            bill_residue.setTextColor(MConst.expendTextColor)
        } else{
            val percent = (residue / budgetNo * 100).toInt()
            bill_progress.setProgress(percent)
            bill_residue.text = "预算剩余: " + residue.toString()
            bill_residue.setTextColor(MConst.incomeTextColor)
        }
    }

    private fun initView() {
        bill_back.setOnClickListener({finish()})
        bill_mouth.setText(currentMouthOfYear)
        bill_mouth.setOnClickListener {
            getDatePickerDialog(object: DatePickerDialog.OnDateSetListener{
                override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                    var choseTime = year.toString() + "年"
                    var mon = month + 1
                    if (month.toString().length == 1){
                        choseTime += "0" + mon.toString()
                    } else{
                        choseTime += mon.toString()
                    }
                    startActivity<BillActivity>(
                            MConst.CURRENT_MOUTH_WITH_YEAR to choseTime
                    )
                    finish()
                }

            }).show()
        }
        bill_add.setOnClickListener({
            startActivity<BillAddActivity>()
            overridePendingTransition(R.anim.from_bottom_in, R.anim.keep)
        })
        bill_residue.setOnClickListener({ startActivity<BudgetSettingActivitiy>() })
        bill_statistic.setOnClickListener({
            val intent = Intent(this, BillStatisticActivity::class.java)
            intent.putExtra(MConst.CURRENT_MOUTH_WITH_YEAR, currentMouthOfYear)
            startActivity(intent)
        })

        bill_recordRe.layoutManager = LinearLayoutManager(this)
        bill_recordRe.adapter = billAdapter
    }

    /**
     * 监听数据更扁
     */
    override fun onTrigger(action: String, msg: LAMessege) {
        when(action){
            LAction.DB_UPDATE_BILL ->
                    refreshRecordData()
            LAction.ACTION_CHANGE_BUDGET ->
                    refreshBugdet(msg.arg1)

        }
    }


    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        LManager.newInstance().unRegister(this)
    }

    class BillAdapter: RAdapter<CBill>{

        //用于记录日期是否与上次一致，不一致则显示日期
        private var lastRecordDay = ""

        override fun conver(holder: RViewHolder, data: CBill) {
            val timeLayout: LinearLayout = holder.getView(R.id.adapter_bill_timeLayout)!!
            val timeText: TextView = holder.getView(R.id.adapter_bill_time)!!
            val icon: ImageView = holder.getView(R.id.adapter_bill_typeIcon)!!
            val total = holder.getView<TextView>(R.id.adapter_bill_total)!!
            val specific = holder.getView<TextView>(R.id.adapter_bill_specific)!!

            var time = data.createTime
            val endIndex = time.indexOf("日")
            val startIndex = time.indexOf("年") + 1
            time = time.substring(startIndex..endIndex)
            //根据情况显示或隐藏日期
            if (lastRecordDay.equals(time)){
                timeLayout.visibility = View.GONE
            } else{
                timeLayout.visibility = View.VISIBLE
                lastRecordDay = time
            }

            timeText.text = time
            specific.text = data.specific
            icon.setImageResource(RecordHelper.getBillIcon(data.type!!, data.specific!!))

            // 根据收入支出类型改变颜色
            if (data.type.equals(MConst.BILL_INCOME)){
                total.text = "+" + data.total
                total.setTextColor(MConst.incomeTextColor)
            } else{
                total.text = "-" + data.total
                total.setTextColor(MConst.expendTextColor)
            }

            // 跳转
            val mainLayout = holder.getView<LinearLayout>(R.id.adapter_bill_mainLayout)!!
            mainLayout.setOnClickListener({
                val intent: Intent = Intent(mContext, BillModifyActivity::class.java)
                intent.putExtra("cbill",data)
                mContext.startActivity(intent)
            })
        }

        override fun setDatas(datas: MutableList<CBill>) {
            super.setDatas(datas)
            lastRecordDay = ""
        }

        constructor(context: Context, layoutId: Int, bills: MutableList<CBill> = mutableListOf()):
                super(context, layoutId, bills)
    }

}
